package com.atguigu.springcloud.controller;

import cn.hutool.core.util.IdUtil;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private Integer serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id) {
        return "线程池: " + Thread.currentThread().getName() + " paymentInfo_OK id: " + id + "\to(n_n)o哈哈~";
    }

    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "6000")
    })
    // @HystrixCommand(defaultFallback = "paymentInfo_TimeoutHandler")
    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_Timeout(@PathVariable("id") Integer id) {
        int number = 10;
//        int age = 10/0;
        try {
            TimeUnit.SECONDS.sleep(number);
        } catch (InterruptedException e) {
//            e.printStackTrace();
            log.error("***** 触发超时错误");
        }
        return "线程池: " + Thread.currentThread().getName() + " paymentInfo_Timeout id: " + id + "\to(n_n)o哈哈~" + " 耗时"+number+"秒钟";
    }

    // callback paymentInfo_Timeout
    public String paymentInfo_TimeoutHandler(Integer id) {
        return "线程池: " + Thread.currentThread().getName() + " paymentInfo_TimeoutHandler id: " + id + "\tー(￣～￣)ξo~";
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("***** service: " + service);
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                log.info("***** instance: " +
                        instance.getInstanceId() + " " +
                        instance.getHost() + " " + " " +
                        instance.getScheme() + " " +
                        instance.getHost() + " " +
                        instance.getServiceId() + " " +
                        instance.getMetadata() + " " +
                        instance.getUri());
            }
        }
        return discoveryClient;
    }

    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("*****插入结果: " + result);

        if (result > 0) {
            return new CommonResult(200, "插入数据成功@" + serverPort, result);
        } else {
            return new CommonResult(444, "插入数据失败", null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment result = paymentService.getPaymentById(id);
        log.info("*****插入结果: " + result);

        if (result != null) {
            return new CommonResult<>(200, "查询数据成功@" + serverPort, result);
        } else {
            return new CommonResult<>(444, "没有对应记录", null);
        }
    }

    @GetMapping(value = "/payment/get-timeout/{id}")
    public CommonResult<Payment> getPaymentByIdWithTimeout(@PathVariable("id") Long id) {
        Payment result = null;

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
        }

        result = paymentService.getPaymentById(id);
        log.info("*****插入结果: " + result);

        if (result != null) {
            return new CommonResult<>(200, "查询数据成功@" + serverPort, result);
        } else {
            return new CommonResult<>(444, "没有对应记录", null);
        }
    }



    // 服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60") // 失败后率达到多少百分比开始跳闸
    })
    @GetMapping("/payment/circuit/{id}")
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("***** id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功, 流水号: " + serialNumber;
    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) {
        return "id 不能负数, 请稍后再试... " + id;
    }

}
